<template>
  <a-modal
    :visible="visible"
    :ok-loading="loading"
    :title="title"
    @ok="submit"
    @cancel="close"
  >
    <a-form ref="formRef" :size="form.size" :model="form">
      <a-form-item
        field="name"
        label="名称"
        :rules="[{ required: true, message: '名称不能为空' }]"
        :validate-trigger="['change', 'input']"
      >
        <a-input v-model="form.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item
        field="number"
        label="数量"
        :rules="[
          { required: true, message: '数量不能为空' },
          { type: 'number', max: 200, message: '数量不能超过200' },
        ]"
      >
        <a-input-number v-model="form.number" placeholder="请输入数量" />
      </a-form-item>

      <a-form-item
        field="price"
        label="价格"
        :rules="[{ required: true, message: '价格不能为空' }]"
      >
        <a-input-number v-model="form.price" placeholder="请输入价格" />
      </a-form-item>

    
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, reactive, toRefs, onMounted, toRaw } from 'vue'
import { api } from '~/util/ajax'
import { Message } from '@arco-design/web-vue'
const data = reactive({
  visible: false,
  loading: false,
  title: '添加页面',
  form: {
    size: 'medium',
    name: '',
    number: undefined,
    price: '',
    number: '',
  },
})
let { form, visible, loading } = toRefs(data)
let formRef = ref()

onMounted(() => {
  console.log(form.value)
  // console.log(box.value);
  console.log(formRef.value)
})

const add = () => {
  data.visible = true
  data.title = '添加'
}

const edit = (val) => {
  data.visible = true
  data.title = '修改'
  //拷贝没有就添加，有就覆盖
  Object.assign(data.form, val)
}
expose({
  add, // 明确的暴露接口
  edit,

})

function submit() {
  formRef.value.validate((err) => {
    if (err) return
    // const input = form.value
    data.loading = true
    let _modelRef = { ...toRaw(form.value) }
    // let _api = _modelRef.id ? putData : postData
    if (_modelRef.id) {
      api.post('/put', _modelRef).then((res) => {
        if (res.result) {
          close()
      
          Message.success(data.title + '成功！')
        } else {
          Message.error(data.title + '失败！' || res.errorMessage)
        }
      })
    } else {
      api.post('/add', _modelRef).then((res) => {
        if (res.result) {
          close()
        
          Message.success(data.title + '成功！')
        } else {
          Message.error(data.title + '失败！' || res.errorMessage)
        }
      })
    }
  })
}

const emit = defineEmits(['close'])

function close() {
  formRef.value.clearValidate()
  formRef.value.resetFields()
  data.loading = false
  data.visible = false
  emit('ok')
}
</script>
